<template>
  <div class="login-container">
    <a-card class="login-card" title="农产品供销平台">
      <!-- 移除tabs组件 -->
      <div class="login-content">
        <a-form
          :model="accountForm"
          @finish="handleAccountLogin"
        >
          <a-form-item
            name="user"
            :rules="[{ required: true, message: '请输入用户名/邮箱/手机号' }]"
          >
            <a-input
              v-model:value="accountForm.user"
              placeholder="请输入用户名"
            >
              <template #prefix>
                <UserOutlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item
            name="userPassword"
            :rules="[{ required: true, message: '请输入密码' }]"
          >
            <a-input-password
              v-model:value="accountForm.userPassword"
              placeholder="请输入密码"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" html-type="submit" block class="login-btn">
              立即登录
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <div class="login-footer">
        <span class="tip-text">还没有账号？</span>
        <a-button type="link" class="register-btn" @click="showRegisterModal">
          立即注册
        </a-button>
      </div>
      
      <!-- 农户注册弹窗 -->
      <a-modal
        v-model:visible="registerModalVisible"
        title="农户注册"
        :width="500"
        :footer="null"
      >
        <a-form
          :model="registerForm"
          :rules="registerRules"
          @finish="handleRegister"
          layout="vertical"
        >
          <a-form-item label="用户名" name="userName" required>
            <a-input v-model:value="registerForm.userName" placeholder="请输入用户名" />
          </a-form-item>
          
          <a-form-item label="密码" name="password" required>
            <a-input-password v-model:value="registerForm.password" placeholder="请输入密码" />
          </a-form-item>
          
          <a-form-item label="确认密码" name="checkPassword" required>
            <a-input-password v-model:value="registerForm.checkPassword" placeholder="请再次输入密码" />
          </a-form-item>
          
          <a-form-item label="手机号" name="phone" required>
            <a-input v-model:value="registerForm.phone" placeholder="请输入手机号" />
          </a-form-item>
          
          <a-form-item label="农户名称" name="farmName" required>
            <a-input v-model:value="registerForm.farmName" placeholder="请输入农户名称" />
          </a-form-item>
          
          <a-form-item label="描述" name="farmDesc">
            <a-textarea v-model:value="registerForm.farmDesc" placeholder="请输入描述" :rows="3" />
          </a-form-item>
          
          
          <a-form-item>
            <a-button type="primary" html-type="submit" block class="register-btn">
              立即注册
            </a-button>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
// 保持原有脚本部分不变
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import { userLoginUsingPost, getLoginUserUsingGet } from '@/api/userController'
import { addFarmersUsingPost } from '@/api/farmersController'
import { useUserStore } from '@/stores/user'

const router = useRouter();
const userStore = useUserStore();

// 登录表单
const accountForm = ref({
  user: '',
  userPassword: ''
});

// 注册相关
const registerModalVisible = ref(false);
const registerForm = reactive({
  userName: '',
  password: '',
  checkPassword: '',
  phone: '',
  farmName: '',
  farmDesc: ''
});

// 注册表单验证规则
const registerRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度必须在2-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  farmName: [
    { required: true, message: '请输入农户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '农户名称长度必须在2-50个字符之间', trigger: 'blur' }
  ]
};

// 密码确认验证
function validatePassword(_rule: any, value: string) {
  if (value === '') {
    return Promise.reject('请再次输入密码');
  }
  if (value !== registerForm.password) {
    return Promise.reject('两次输入的密码不一致');
  }
  return Promise.resolve();
}

// 显示注册弹窗
const showRegisterModal = () => {
  registerModalVisible.value = true;
};

// 处理注册
const handleRegister = async () => {
  try {
    // 调用注册接口
    const res = await addFarmersUsingPost(registerForm);
    // @ts-ignore
    if (res.code === 0 && res.data) {
      message.success('注册成功，请登录');
      registerModalVisible.value = false;
      // 清空表单
      Object.keys(registerForm).forEach(key => {
        // @ts-ignore
        registerForm[key] = '';
      });
    } else {
      // @ts-ignore
      message.error(res.message || '注册失败');
    }
  } catch (error) {
    console.error('注册出错:', error);
    message.error('注册失败，请稍后重试');
  }
};

// 登录处理
const handleAccountLogin = async (values: any) => {
  try {
    const res = await userLoginUsingPost(values)
    // @ts-ignore
    if (res.code === 0 && res.data) {
      // 先设置token
      // @ts-ignore
      userStore.setToken(res.data || '')
      // 获取用户信息
      const userInfo = await userStore.fetchUserInfo()
      
      // 检查用户身份，只允许管理员或农户登录
      // @ts-ignore
      if (userInfo && (userInfo.userRole === 'admin' || userInfo.userRole === 'farmer')) {
        message.success('登录成功')
        router.push('/')
      } else {
        // 如果不是管理员或农户，清除token并提示
        userStore.clearToken()
        message.error('您没有权限登录管理系统，请使用管理员或农户账号')
      }
    } else {
      // @ts-ignore
      message.error(res.message || '登录失败')
    }
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  position: relative;
  overflow: hidden;
}

.login-card {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  border-radius: 16px;
  overflow: hidden;
  background: rgba(255,255,255,0.98);
  animation: cardEntrance 0.6s ease-out;
}

.login-card::before {
  background: linear-gradient(45deg,
  rgba(255,183,77,0.08) 25%,
  transparent 25%,
  transparent 50%,
  rgba(255,183,77,0.08) 50%,
  rgba(255,183,77,0.08) 75%,
  transparent 75%);
}

/* 输入框样式 */
:deep(.ant-input),
:deep(.ant-input-password) {
  border: 1px solid #ffe0b2;
}

:deep(.ant-input-affix-wrapper:hover),
:deep(.ant-input-affix-wrapper-focused) {
  border-color: #ffb74d !important;
  box-shadow: 0 0 0 2px rgba(255,183,77,0.1);
}

.input-icon {
  color: #ffb74d;
}

/* 按钮样式 */
.login-btn:deep(.ant-btn-primary),
.register-btn:deep(.ant-btn-primary) {
  background: linear-gradient(45deg, #ffd8a8, #ffab66);
  border-color: #ffab66;
}

.login-btn:deep(.ant-btn-primary:hover),
.register-btn:deep(.ant-btn-primary:hover) {
  background: linear-gradient(45deg, #ffab66, #ff9800);
  box-shadow: 0 3px 12px rgba(255,171,102,0.2);
}

/* 页脚链接 */
.register-btn:deep(.ant-btn-link) {
  color: #ffab66 !important;
  font-weight: 500;
}

.register-btn:deep(.ant-btn-link:hover) {
  color: #ff9800 !important;
  text-decoration: underline;
}

/* 登录页脚 */
.login-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 16px;
}

.tip-text {
  color: #666;
  margin-right: 4px;
}

/* 注册弹窗样式 */
:deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.ant-modal-header) {
  background-color: #fff9f0;
  border-bottom: 1px solid #ffe0b2;
}

:deep(.ant-modal-title) {
  color: #ff9800;
  font-weight: 600;
}

:deep(.ant-form-item-label > label) {
  color: #666;
  font-weight: 500;
}

:deep(.ant-form-item-required::before) {
  color: #ff9800 !important;
}
</style>

